import axios from "axios";
import { useEnv } from "@/hooks/useEnv";
import { message as Message } from "antd";
import { delay, stringToJson } from "@/utils/utils";
// import ipcRender from "@/ipcRender";
import userStore from "@/store/UserStore";
// import WebIM from "@/net/WebIM";

const { BASE_URL, DEV } = useEnv();

let deviceId = "";

const request: any = axios.create({
  timeout: 90000, // 请求超时 90 秒
  headers: { "Content-Type": "application/json;charset=UTF-8" },
  baseURL: BASE_URL,
  maxRedirects: 0, // 设置最大重定向次数
  validateStatus(status) {
    return status >= 200 && status < 300;
  },
});

/**
 * 请求拦截器
 */
request.interceptors.request.use(
  async (config) => {
    // 给 GET 请求加上时间戳参数，避免从缓存中拿数据。
    if (config.method === "get") {
      const params = config.params || {};
      config.params = Object.assign(params, {
        time: new Date().getTime() / 1000,
      });
    } else if (config.method === "post" && config.formData) {
      // 将 JSON 对象转换为 FormData 对象
      const data = stringToJson(config.data) || {};
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
      config.headers["Content-Type"] = "multipart/form-data;charset=UTF-8";
      config.data = formData;
    }

    if (userStore.token) {
      config.headers!["access_token"] = userStore.token;
    }

    config.headers!["client"] = "pcapp";
    if (!deviceId) {
      deviceId = await ipcRender.getDeviceId();
    }

    config.headers!["deviceid"] = deviceId;

    return config;
  },
  (error) => {
    return Promise.reject(new Error(error || "Error"));
  }
);

/**
 * 响应拦截器
 */
request.interceptors.response.use(
  (response: any) => {
    const { data } = response;

    if (!data) {
      return Promise.reject(new Error("请求出错，请稍候重试！"));
    }

    // 响应数据为二进制流处理(Excel导出)
    const contentType = response.headers["content-type"];

    if (
      contentType.startsWith("application/octet-stream") ||
      contentType.startsWith("image/") ||
      contentType.startsWith("video/") ||
      contentType.startsWith("audio/") ||
      contentType.startsWith("text/") ||
      contentType.startsWith(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      ) ||
      contentType === "application/pdf"
    ) {
      return data;
    }

    const { resultCode, resultMsg } = data;
    if (resultCode === 1) {
      return data;
    }

    // 响应数据为二进制流处理(Excel导出)
    if (data instanceof ArrayBuffer) {
      return data;
    }

    ipcRender.log(
      `request error: url：${response.config.url} data：${JSON.stringify(data)}`
    );

    handleError(data.resultCode, data.resultMsg);
    return Promise.reject(resultMsg || "Error");
  },
  (error) => {
    const { response, message } = error || {};
    const errorMsg = response?.data?.resultMsg || message || "Error";

    handleError(response?.data?.resultCode, errorMsg);
    return Promise.reject(errorMsg);
  }
);

/**
 * 错误处理
 * @param code 错误状态码
 * @param message 错误消息
 */
async function handleError(code, message) {
  switch (code) {
    case 1030101:
    case 1030102:
      Message.error(message);
      await delay(500);
      await WebIM.logout();
    default:
  }
  // 已经替换了一部分提示  就统一使用这里吧，然后逐步替换重复提示
  Message.error(message);
}
export default request;
